﻿using Game.Util;
using Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using UnityEngine;
using Util;

namespace Game
{
    public partial class NetManager
    {
        public void OnMessage(MessageBuffer msg)
        {
            int cproto = msg.ReadInt();
            Debug.Log(cproto);
            switch (cproto)
            {
                case cProto.CONNECT:
                    //CONNECT协议处理（玩家连接）:服务器分配玩家ID并确立客户端身份
 //                   SceneManager.instance.InitViewMap();
                    int roleId = msg.ReadInt();
//                    SceneManager.instance.viewMap.CreateMe(roleId);
                    SceneManager.instance.viewMap.LogicMap.curRoleId = roleId;
                    Debug.Log("玩家,id = " + roleId);
                    break;
                case cProto.READY:
                    break;
                case cProto.SYNC_POS:
                    //50ms间隔同步位置
                    int cRoleId = msg.ReadInt();
                    string pos = msg.ReadString();
                    
                    //更新其他玩家的位置
                    SceneManager.instance.viewMap.SyncPos(cRoleId, pos);
                    Debug.Log(string.Format("玩家 {0} ,pos = {1}", cRoleId ,pos));
                    break;
                case cProto.SYNC_KEY:
                    //关键帧
                    int servFrameCount = msg.ReadInt();
                    
                    //确保只处理新帧/补帧
                    if (servFrameCount >= SceneManager.instance.viewMap.LogicMap.curFrameCount)
                    {
                        string keyStr = msg.ReadString();
                        string[] keyData = keyStr.Split(';');
                        for (int i = 0; i < keyData.Length; ++i )
                        {
                            if(keyData[i] == "")
                            {
                                continue;
                            }
                            KeyData data = new KeyData(keyData[i]);
                            
                            //执行所有的命令
                            SceneManager.instance.viewMap.LogicMap.DoCmd(data);
                        }
                        SceneManager.instance.viewMap.LogicMap.curFrameCount += 1;
                    }                   
                    break;
                case cProto.START:
                    string players = msg.ReadString();
                    SceneManager.instance.viewMap.CreateAllPlayer(players);
                    
                    //启动定时器，间隔50毫秒同步自身的位置
                    TimerHeap.AddTimer(0, 40, SycMePos);
                    
                    //启动定时器，间隔100毫秒同步自身技能作为关键帧率
                    TimerHeap.AddTimer(0, 80, SycKey);
                    break;
            }
        }
    }
}
